use model_graph_types::{
    database::DataSource,
    modeling::{Class, ClassPersistence, ModelingSqlGenerator},
};

use crate::sql::attribute_sql;

#[derive(Debug, Default)]
pub struct MySQLSqlGenerator {}

//
#[async_trait::async_trait]
impl ModelingSqlGenerator for MySQLSqlGenerator {
    /// 类型的DDL
    async fn class_struct_sql(
        &self,
        meta_datasource: &DataSource,
        class: Class,
        persistence: ClassPersistence,
    ) -> anyhow::Result<String> {
        //建表

        let mut columns: Vec<String> = vec![];
        if let Some(attributes) = &class.attributes {
            for attribute in attributes {
                if !attribute.is_persistent {
                    continue;
                }
                //
                columns.push(attribute_sql(attribute)?);
            }
        }

        let table_name = persistence.table_name.clone();

        let sql = format!(" CREATE TABLE `{}`(\n\t{},\n\tPRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='' ", table_name, columns.join(",\n\t"));

        tracing::debug!("sql:{}", sql);
        Ok(sql)
    }
}
